import app from '@/app'
import Factory from './factory'
import { total } from '@/api/store/order'

class OrderFactory extends Factory {

  async getData(start, end, data) {
    const res = await total({ time: [start.unix(), end.unix()] })

    // 因为有多线程，就直接填充
    if(res.count > 0) {
      data.c = res.count
      data.pm = res.profit_money
      data.cm = res.cost_money
      data.rm = res.req_money
      data.tm = res.tax_money
      data.t = res.total
    }
  }

  // 处理统计
  total() {
    // 统计字段
    const fields = ['t', 'c', 'pm', 'cm', 'rm', 'tm']

    // 循环天
    this.day.forEach(data => {
      if(data.c) {
        // 循环要统计的字段
        fields.forEach(field => {
          const value = data[field]
          // 统计年
          this.year[field] = app.math.add(this.year[field] ?? 0, value)
          // 统计季度 
          this.quarter[data.id[0]][field] = app.math.add(this.quarter[data.id[0]][field] ?? 0, value)
          // 统计月
          this.month[data.id[1]][field] = app.math.add(this.month[data.id[1]][field] ?? 0, value)
        })
      }
    })
  }

  // 查询统计数据
  getTotal(type, index, day) {
    return {
      year: () => {
        return {
          data: this.year,
          list: this.month
        }
      },
      quarter: () => {
        const list = this.getDayList({ quarter: index })
        return {
          data: this.quarter[index],
          list,
          time: list.map(item => {
            return this.getDayTime(item).dateSmall()
          })
        }
      },
      month: () => {
        const list = this.getDayList({ month: index })
        return {
          data: this.month[index],
          list: list,
          time: list.map(item => {
            return this.getDayTime(item).dateSmall()
          })
        }
      },
      day: () => {
        const data = this.getDay(day.month(), day.day())
        return {
          data,
          list: [data],
          time: [this.getDayTime(data).dateSmall()]
        }
      }
    }[type]()
  }
}

export default OrderFactory